<!--  -->
<template>
  <div class="comment">
    <h3 class="comment-title">发表评论</h3>
    <hr />
    <textarea
      placeholder="请输入要评论的内容（最多吐槽120字）"
      v-model="msg"
    ></textarea>
    <button class="btn send" size="large" @click="postComment">发表评论</button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item, i) in comments" :key="item.add_time">
        <div class="cmt-title">
          第{{ i + 1 }}楼&nbsp;&nbsp;用户：{{
            item.user_name
          }}
          &nbsp;&nbsp;发表时间:{{ item.add_time | dateFormat }}
        </div>
        <div class="cmt-body">
          {{
            item.content === "underfined" ? "此用户很懒,啥都没说" : item.content
          }}
        </div>
      </div>
    </div>
    <button class="btn more" @click="getMore" size="large">加载更多</button>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
export default {
  components: {},
  data() {
    return {
      pageIndex: 1,
      comments: [],
      msg: "",
      newsId: this.$route.params.id,
    };
  },
  props: ["id"],
  computed: {},
  created() {
    this.getComment();
  },
  methods: {
    //获取评论
    getComment() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageIndex)
        .then((res) => {
          if (res.body.status === 0) {
            // this.comments = res.body.message;
            this.comments = this.comments.concat(res.body.message);
            console.log(res);
          } else {
            Toast("数据加载失败");
          }
        });
    },
    getMore() {
      this.pageIndex++;
      this.getComment();
    },
    //发表评论 参数1：请求user地址 参数2：提交给服务器的数据对象 参数3：定义提交格式
    postComment() {
        if(this.msg.trim().length===0){
            return  Toast('评论内容不能为空')
        }
      this.$http
        .post("api/postcomment/" + this.newsId, { content:this.msg.trim()})
        .then(function(res){
            if(res.body.status===0){
              // 1 拼接评论对象
              var cmt={user_name:'匿名用户',add_time:Date.now(),content:this.msg.trim()};
              // 2 
            }
            this.comments.unshift(cmt);
            this.msg=''
        });
    },
  },
};
</script>
<style lang='scss' scoped>
.comment {
  .comment-title {
    font-size: 16px;
    margin-bottom: 10px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
    margin-top: 10px;
  }
  .cmt-list {
    font-size: 13px;
    .cmt-title {
      background: #ccc;
      margin: 4px 0;
      line-height: 30px;
    }
    .cmt-body {
      text-indent: 2rem;
      line-height: 30px;
    }
  }
  .btn {
    width: 100%;
    text-align: center;
    padding: 10px 0;
    font-size: 16px;
    border: none;
  }
  .send {
    color: white;
    background: #26a2ff;
  }
  .more {
    color: red;
    border: 1px solid red;
  }
}
</style>